/*
 * *
 *  * Created with IntelliJ RustRover.
 *  * Description:
 *  * Copyright Author: ZhenYi
 *  * DateTime: 2024/2/15 下午6:34
 *
 */

use salvo::prelude::*;
use sea_orm::EntityTrait;
use serde::{Deserialize, Serialize};
use crate::config::pgsql::maunlist;

#[derive(Serialize, Deserialize)]
struct MaunListInput{
    nums:String,
    page:String,
    stage:String,
}
#[handler]
pub async fn get_maun_list(req: &mut Request, depot: &mut Depot, res: &mut Response){
    let db = depot.obtain::<sea_orm::DatabaseConnection>().unwrap();
    let input = match req.parse_json::<MaunListInput>().await{
        Ok(input) => input,
        Err(e) => {
            res.status_code(StatusCode::IM_USED).render(e.to_string());
            return;
        }
    };
    let page = match input.page.parse::<i32>() {
        Ok(page) => page,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Page should be a number\"}");
            return;
        }
    };
    let nums = match input.nums.parse::<i32>() {
        Ok(nums) => nums,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Nums should be a number\"}");
            return;
        }
    };
    let stage = match input.stage.parse::<i32>() {
        Ok(stage) => stage,
        Err(_) => {
            res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Stage should be a number\"}");
            return;
        }
    };

    if stage > 11 || stage < -1 {
        res.status_code(StatusCode::IM_USED).render("{\"Error\":\"Stage should be a number between -1 and 11\"}");
        return;
    }

    if stage == -1{
        let ds = maunlist::Entity::find()
            .all(db)
            .await
            .unwrap();
        let mut r = Vec::new();
        for (us,nd) in ds.iter().enumerate(){
            if page*nums > us as i32 {
                continue
            }
            if (page+1)*nums < us as i32{
                break
            }
            r.push(nd);
        }
        res.status_code(StatusCode::ACCEPTED).render(serde_json::to_string(&r).unwrap());
        return;
    }else {
        let ds = maunlist::Entity::find()
            .all(db)
            .await
            .unwrap();
        let mut r = Vec::new();
        for (us,nd) in ds.iter().enumerate(){
            if nd.stage != stage {
                continue
            }
            if page*nums > us as i32 {
                continue
            }
            if (page+1)*nums < us as i32{
                break
            }
            r.push(nd);
        }
        res.status_code(StatusCode::ACCEPTED).render(serde_json::to_string(&r).unwrap());
        return;
    }
}